package 链表;

/**
 * 876. 链表的中间结点 (https://leetcode-cn.com/problems/middle-of-the-linked-list/)
 * 给定一个头结点为 head 的非空单链表，返回链表的中间结点。如果有两个中间结点，则返回第二个中间结点。
 * <p>
 * 1、
 * <p/>
 * User: zhaixiaolong Date:2024/1/4 13:55 ProjectName: algorithm Version: V
 */
public class 链表中间节点 {

    /**
     * 初始化链表
     *
     * @return
     */
    public static Node initData() {
        Node node1 = new Node();
        node1.value = 1;
        Node node2 = new Node();
        node2.value = 2;
        Node node3 = new Node();
        node3.value = 3;
        Node node4 = new Node();
        node4.value = 4;
        Node node5 = new Node();
        node5.value = 5;
        Node node6 = new Node();
        node6.value = 6;

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        return node1;
    }


    /**
     * 1、2、3、4、5、6
     * 快慢指针
     *
     * @param head
     * @return
     */
    public static Node findCenterNode(Node head) {
        if (head.next == null) {
            return head;
        }
        Node before = head;
        Node after = head;
        while (before != null && before.next != null) {
            before = before.next.next;
            after = after.next;
        }
        return after;

    }

    public static void main(String[] args) {
        Node centerNode = findCenterNode(initData());
        System.out.println(centerNode.value);
    }
}
